package com.lijinjiang.view;

import com.lijinjiang.model.GlobalContext;
import com.lijinjiang.model.tree.ServerConnection;
import com.lijinjiang.util.ImageUtil;

import javax.swing.*;
import java.awt.*;

/**
 * @ClassName SCDialog
 * @Description 新建服务器连接的界面
 * @Author Li
 * @Date 2022/8/15 12:54
 * @ModifyDate 2022/8/15 12:54
 * @Version 1.0
 */
public class SCDialog extends JDialog {
    // 全局上下文环境
    private GlobalContext ctx;
    // 主界面
    private MainFrame mainFrame;
    // 传递过来的服务器连接信息
    private ServerConnection sc;

    // 标签及输入框
    private JLabel nameLabel = new JLabel("连接名");
    private JTextField nameField = new JTextField();
    private JLabel hostLabel = new JLabel("IP地址");
    private JTextField hostField = new JTextField();
    private JLabel portLabel = new JLabel("端口号");
    private JTextField portField = new JTextField();
    private JLabel userLabel = new JLabel("用户名");
    private JTextField userField = new JTextField();
    private JLabel passwordLabel = new JLabel("密    码");
    private JPasswordField passwordField = new JPasswordField();
    private JButton testSCBtn = new JButton("连接测试");
    private JButton confirmBtn = new JButton("确定");
    private JButton cancelBtn = new JButton("取消");

    /**
     * 新建连接
     * @param ctx
     * @param mainFrame
     */
    public SCDialog(GlobalContext ctx, MainFrame mainFrame) {
        this.ctx = ctx;
        this.mainFrame = mainFrame;
        this.setTitle("MySQL - 新建连接");
        hostField.setText("127.0.0.1"); // 设置默认 IP 为 127.0.0.1
        portField.setText("3306"); // 设置默认端口 3306
        userField.setText("root"); // 设置默认用户为 root
        // 新建时的确定按钮：保存连接信息
        confirmBtn.addActionListener(e -> {
            // 得到用户输入的信息，并返回一个ServerConnection
            ServerConnection sc = getCurrentSC();
            if (!dataValidate(sc)) {
                JOptionPane.showMessageDialog(SCDialog.this, "配置信息不能为空，请补充完整！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // 判断连接名是否重复
            if (this.ctx.getSC(sc.getName()) != null) {
                JOptionPane.showMessageDialog(SCDialog.this, "已存在命名为" + sc.getName() + "的连接！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // 直接保存，不需要创建任何连接
            this.ctx.addSC(sc);
            // 保存到属性文件
            this.ctx.getPropertiesHandler().saveSC(sc);
            // 刷新树节点中的连接
            this.mainFrame.getLeftPane().addSCNode(sc);
            this.dispose();
        });
        this.init();
    }


    /**
     * 编辑连接
     * @param ctx
     * @param mainFrame
     * @param sc
     */
    public SCDialog(GlobalContext ctx, MainFrame mainFrame, ServerConnection sc) {
        this.ctx = ctx;
        this.mainFrame = mainFrame;
        this.sc = sc;
        this.setTitle("MySQL - 编辑连接");
        if (this.sc != null) {
            this.nameField.setText(sc.getName());
            this.hostField.setText(sc.getHost());
            this.portField.setText(sc.getPort());
            this.userField.setText(sc.getUser());
            passwordField = new JPasswordField(sc.getPassword()); // 用原密码初始化一个密码输入框
        }
        confirmBtn.addActionListener(e -> {
            // 得到用户输入的信息，并返回一个 ServerConnection
            ServerConnection newSc = getCurrentSC();
            if (!dataValidate(newSc)) {
                JOptionPane.showMessageDialog(this, "配置信息不能为空，请补充完整！",
                        "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // 名称已修改且与已有的连接名称重复
            if (!newSc.getName().equals(sc.getName()) && this.ctx.getSC(newSc.getName()) != null) {
                JOptionPane.showMessageDialog(this, "已存在命名为" + newSc.getName() + "的连接！",
                        "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            // 将旧连接文件删除
            this.ctx.removeSC(sc);
            // 将新连接添加到全局配置
            this.ctx.addSC(newSc);
            // 保存到属性文件
            this.ctx.getPropertiesHandler().saveSC(newSc);
            this.mainFrame.getLeftPane().refreshSCNode(newSc);
            this.dispose();
        });
        this.init();
    }

    /**
     * 初始化操作
     */
    public void init() {
        this.setIconImage(ImageUtil.CONNECTION_OPEN_IMAGE); // 设置 logo
        this.setSize(new Dimension(300, 340)); // 设置大小
        this.setLayout(null); // 布局格式为空布局
        // 把所有组件全部加到窗口上
        nameLabel.setBounds(30, 30, 60, 30);
        nameField.setBounds(100, 30, 150, 30);
        this.add(nameLabel);
        this.add(nameField);
        hostLabel.setBounds(30, 70, 60, 30);
        hostField.setBounds(100, 70, 150, 30);
        this.add(hostLabel);
        this.add(hostField);
        portLabel.setBounds(30, 110, 60, 30);
        portField.setBounds(100, 110, 150, 30);
        this.add(portLabel);
        this.add(portField);
        userLabel.setBounds(30, 150, 60, 30);
        userField.setBounds(100, 150, 150, 30);
        this.add(userLabel);
        this.add(userField);
        passwordLabel.setBounds(30, 190, 60, 30);
        passwordField.setBounds(100, 190, 150, 30);
        testSCBtn.setBounds(30, 240, 80, 30);
        confirmBtn.setBounds(120, 240, 60, 30);
        cancelBtn.setBounds(190, 240, 60, 30);
        this.add(passwordLabel);
        this.add(passwordField);
        this.add(testSCBtn);
        this.add(confirmBtn);
        this.add(cancelBtn);
        // 测试连接
        testSCBtn.addActionListener(e -> {
            ServerConnection sc = getCurrentSC();
            if (!dataValidate(sc)) {
                JOptionPane.showMessageDialog(SCDialog.this,
                        "配置信息不能为空，请补充完整！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            try {
                sc.connect();
                JOptionPane.showMessageDialog(SCDialog.this, "连接成功", "成功", JOptionPane.OK_OPTION);
            } catch (Exception exception) {
                String message = exception.getMessage();
                JOptionPane.showMessageDialog(SCDialog.this, message, "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelBtn.addActionListener(e -> {
            this.dispose();
        });

        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // 设置默认关闭操作
        this.setLocationRelativeTo(mainFrame); // 设置相对传递的组件居中
        this.setModal(true); // 设置为模态框
        this.setVisible(true); // 设置可见
    }

    // 验证数据是否为空
    private boolean dataValidate(ServerConnection sc) {
        if ("".equals(sc.getName().trim())) return false;
        if ("".equals(sc.getHost().trim())) return false;
        if ("".equals(sc.getPort().trim())) return false;
        if ("".equals(sc.getUser().trim())) return false;
        if ("".equals(sc.getPassword().trim())) return false;
        return true;
    }

    // 从当前界面获取连接信息
    private ServerConnection getCurrentSC() {
        String name = this.nameField.getText();
        String host = this.hostField.getText();
        String port = this.portField.getText();
        String user = this.userField.getText();
        String password = new String(this.passwordField.getPassword());
        return new ServerConnection(name, host, port, user, password);
    }
}
